package com.cdream.basic.algorithm.leetcode.findElement;

import java.util.Arrays;

/**
 * @author cdream
 * @date 5/22/21
 */
public class Question16 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        if (nums.length < 3) {
            return 0;
        }
        int res = nums[0] + nums[1] + nums[2];
        int abs = Math.abs(res - target);
        for (int i = 0; i < nums.length - 2; i++) {

            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int tempSum = nums[i] + nums[left] + nums[right];
                if (tempSum == target) {
                    return tempSum;
                }
                int tempRes = Math.abs(tempSum - target);
                if (tempRes < abs) {
                    res = tempSum;
                    abs = tempRes;
                }
                if (tempSum > target) {
                    right--;
                } else {
                    left++;
                }
            }

        }
        return res;
    }
}
